package cn.gaaidou.common.utils;

import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Martin
 * @date 2021/6/28 20:27
 */
public class IOUtil {

    /**
     * 使用lambada表达式会出现读取阻塞的问题
     * 反复对比实验发现 inputStream.read(buffer) 本身就是自循环，
     * 如果放在循环里面就会死循环，后面的 getOutputStream() 无法执行。
     * https://blog.csdn.net/sonichty/article/details/108702410
     *
     * @param is
     * @return
     * @throws IOException
     */
    public static List<String> readSocketLines(InputStream is) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        char[] result = new char[1024 * 4];
        reader.read(result);
        return Arrays.stream(new String(result).split("\n")).map(String::trim).filter(StringUtil::isNotEmpty).collect(Collectors.toCollection(LinkedList::new));
    }

    /**
     * @param is
     * @return
     * @throws IOException
     * @see IOUtil#readSocketLines
     */
    public static byte[] readSocket(InputStream is) throws IOException {
        byte[] result = new byte[1024 * 4];
        is.read(result);
        return result;
    }

    public static PrintWriter buildPrint(OutputStream os) throws IOException {
        return new PrintWriter(new OutputStreamWriter(os));

    }
}
